import { DownOutlined, CarryOutOutlined, ExclamationCircleOutlined, ApiFilled } from '@ant-design/icons';
import { Button, Divider, Dropdown, Menu, message, Modal, Descriptions } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import CreateDefect from './components/CreateDefect';
import { queryPatrolRecordItem, getPatrolRecordInfo, updatePatrolRecordItem, conformPatrolRecord } from '@/services/patrolrecord';
import { history, useModel } from 'umi';
import { convertDefectRecord } from '@/services/defectrecord';
import { queryAreaTree } from '@/services/area';
import UpdateForm from './components/UpdateForm';
import moment from 'moment'


/**
 * 转缺陷
 * @param fields
 */
 const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    console.log(fields);
    await convertDefectRecord(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleConform= async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await conformPatrolRecord(fields);
    hide();
    message.success('确认成功');
    return true;
  } catch (error) {
    hide();
    message.error('确认失败请重试！');
    return false;
  }
};



const { confirm } = Modal;



const TableList: React.FC = (props:any) => {
  const { params } = props.match;
  var unConvertIdlist=[];
  const { initialState } = useModel('@@initialState');
  const { dicts } = initialState || {};
  const [areaData, setAreaData] = useState<API.TreeNodeItem[]>([]);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [leveEnumValues, setLeveEnumValues] = useState({});
  const [unConvertNum, setUnConvertNum] = useState(0);
  const [typeEnumValues, setTypeEnumValues] = useState({});
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState<API.PatrolJobItem>({});
  const [patrolJob, setPatrolJob] = useState<API.PatrolRecord>({});
  const actionRef = useRef<ActionType>();

  const columns: ProColumns[] = [
    {
      title: '巡检区域',
      dataIndex: 'areaName',
    },
    {
      title: '巡检位置',
      dataIndex: 'position',
    },
    {
      title: '巡检内容',
      dataIndex: 'content',
      width:300,
    },
    {
      title: '重要性',
      dataIndex: 'importantLevel',
      valueEnum: leveEnumValues,
    },
    {
      title: '项目类别',
      dataIndex: 'patroItemlType',
      valueEnum: typeEnumValues,
    },
    {
      title: '是否正常',
      dataIndex: 'isWorks',
      valueEnum:  {
        1: { text: '是', status: 'Success' },
        0: { text: '否', status: 'Error' },
      },
    },
    {
      title: '缺陷描述',
      dataIndex: 'defectInfo',
      width:300,
    },
    {
      title: '备注',
      dataIndex: 'memo',
      width:300,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        if(record.isWorks==0 &&record.isConvert==0){
        
          if(!unConvertIdlist.includes(record.id)){
            unConvertIdlist.push(record.id,1)
        }

        }else{
          if(unConvertIdlist.includes(record.id)){
              unConvertIdlist.splice(record.id,1)
          }
        }
        console.log(unConvertIdlist)
        setUnConvertNum(unConvertIdlist.length)
        if(record.isWorks==0 &&record.isConvert==0 &&patrolJob.isConform==0){
          return(
           <a onClick={() => {
                  handleModalVisible(true);
                  setFormValues(record);
                }}
              >
                 转缺陷
              </a>
            
           
          )
        }
     },
    },
  ];

  const setStateData = async () => {
    const patrol = await getPatrolRecordInfo(params);
    setPatrolJob(patrol);
    if (dicts) {
      setLeveEnumValues(dicts["7Enum"]);
      setTypeEnumValues(dicts["4Enum"]);
    }
    let trees = await queryAreaTree();
    setAreaData(trees);

  };

  useEffect(() => {
    unConvertIdlist=[];
     setStateData();
  }, []);

  return (
    <>
      <Descriptions title="巡检记录" style={{ margin: '0px', padding: '24px' }}>
        <Descriptions.Item label="任务名称">{patrolJob.jobName}</Descriptions.Item>
        <Descriptions.Item label="巡检人">{patrolJob.userName}</Descriptions.Item>
        <Descriptions.Item label="值班领导">{patrolJob.dutyLeaderName}</Descriptions.Item>
        <Descriptions.Item label="巡检时间">{patrolJob.patrolTime}</Descriptions.Item>
        <Descriptions.Item label="处理意见">{patrolJob.comment}</Descriptions.Item>
      </Descriptions>
      <ProTable
        headerTitle=""
        rowKey="id"
        actionRef={actionRef}
        tableAlertRender={false}
      
        toolbar={{
          settings: []
        }}
        search={false}
        rowSelection={false}
        request={(param) => queryPatrolRecordItem({ ...params })}
        columns={columns}
        pagination={false}
      />
      {patrolJob.isConform==0? <div style={{    display: 'flex',justifyContent: 'flex-end',marginRight: '24px'}}>   <Button
              icon={<CarryOutOutlined />}
              type="primary"
              onClick={() => {
                let text="您确定要确认吗?";
               
                if(unConvertNum>0){
                  text="您还有未转的缺陷，确定要确认吗?";
                }
                confirm({
                  title:text,
                  icon: <ExclamationCircleOutlined />,
                  async onOk() {
                    handleUpdateModalVisible(true);
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }}>
              确认
            </Button></div>:null}
     
      {formValues && Object.keys(formValues).length ? (
        <CreateDefect
          onSubmit={async (value) => {
            value.defectSource='patrol';
            value.jobRecordId= patrolJob.id;
            value.findPeople=patrolJob.patrolUser;
            value.jobId=patrolJob.jobId;
            value.jobItemId=formValues.id;
        
            const success = await handleAdd(value);
      
            if (success) {
              setUnConvertNum(0);
              console.log(unConvertNum);
              handleModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleModalVisible(false);
            setFormValues({});
          }}
          modalVisible={createModalVisible}
          values={formValues}
          treeData={areaData}
        
        />
      ) : null}

       <UpdateForm
          onSubmit={async (value) => {
            value.id=patrolJob.id;
            const success = await handleConform(value);
            if (success) {
              patrolJob.isConform=1;
              setPatrolJob(patrolJob);
              handleUpdateModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
          }}
          updateModalVisible={updateModalVisible}
         
        />
    </>
  );
};

export default TableList;
